package com.eli.manager;

import java.net.URL;
import java.util.Properties;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.eli.manager.pojo.App;
import com.eli.manager.pojo.PropertiesHelper;

public class Main extends Activity {
	
   
	public static String URL_LIST_PRODUCT = "";
	private static Properties properties;
	
	ListView list_product;
	AppAdapter appAdapter;
	ProgressDialog progress;
	Context context;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		//Get URL_LIST_PRODUCT
		if(URL_LIST_PRODUCT == null || "".equals(URL_LIST_PRODUCT)){
			URL_LIST_PRODUCT = getUrl(this.getApplicationContext());
		}
		
		if(!isOnline()){
			showErrorMessage(this, "Please check to connect Internet or Wifi.");
        	//Toast.makeText(getApplicationContext(), "Please check to connect Internet or Wifi!", Toast.LENGTH_LONG).show();
        	return;
		}else{			
			list_product = (ListView) findViewById(R.id.list_product);
			processing(this);
			setEventClick();
		}
	}
	
	private String getUrl(Context context){
		if (properties == null){
				properties = PropertiesHelper.loadProperties(context);
	    }
		return properties.getProperty(PropertiesHelper.URL_LIST_PRODUCT);
	}
	
	public void processing(Context con){
		this.context = con;
		new AsyncTask<String, Void, Void>() {
			
			@Override
		    protected void onPreExecute() {
		        progress = ProgressDialog.show(context, "", "Loading...", true);
		    }
			
			@Override
			protected Void doInBackground(String... params) {
				appAdapter = new AppAdapter(context, R.layout.display);
				getProduct();
				return null;
			}

			@Override
			protected void onPostExecute(Void arg) {
			    if (progress.isShowing()){
			    	list_product.setAdapter(appAdapter);
			    	progress.dismiss();
			    }
			}
		}.execute("");
	}

	public void setEventClick(){
		list_product.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> list, View view,
					int position, long id) {
				App app = (App) list.getItemAtPosition(position);
				String[] item = { app.getAppname(),app.getIcon(),app.getDescription(),app.getLink(),app.getAppsize(),app.getVersionName()};
				Intent intent = new Intent("com.eli.manager.APPDETAIL");
				intent.putExtra("item", item);
				intent.putExtra("pkg", app.getPname());
				intent.putExtra("verCode", app.getVersionCode());
				startActivity(intent);
			}
		});
	}
	
	public void getProduct() {
		try {
			XmlPullParser xmlPullParser = Xml.newPullParser();

			URL url = new URL(URL_LIST_PRODUCT);
			xmlPullParser.setInput(url.openStream(), "UTF-8");

			App app = null;
			int eventType;
			String name, size, icon, version, link, description,pkg;
			int versionCode=0;
			name = size = icon = version = link = description = pkg = "";
			while ((eventType = xmlPullParser.next()) != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xmlPullParser.getName().equals("name")) {
						name = xmlPullParser.nextText();
					}else if (xmlPullParser.getName().equals("package")) {
						pkg = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("size")) {
						size = xmlPullParser.nextText();
//					} else if (xmlPullParser.getName().equals("icon")) {
//						icon = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version")) {
						version = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version-code")) {
						versionCode = Integer.parseInt(xmlPullParser.nextText());						
					} else if (xmlPullParser.getName().equals("link")) {
						link = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("description")) {
						description = xmlPullParser.nextText();
						app = new App();
						app.setAppname(name);
						app.setPname(pkg);
						app.setAppsize(size);
						//app.setIcon(icon);
						app.setVersionName(version);
						app.setVersionCode(versionCode);
						app.setLink(link);
						app.setDescription(description);
						appAdapter.add(app);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	 private boolean isOnline() {
	        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo ni = cm.getActiveNetworkInfo();
	        if(ni != null && ni.isConnected()){
	            return true;
	        }

	        return false;
	    }
	 
	 	public static void showErrorMessage(Context _context, String message) {
			showMessage(_context, "Error!", message, android.R.drawable.ic_dialog_alert, null);
		}

		
		public static void showMessage(Context _context, String title, String message, int icon, DialogInterface.OnClickListener ackHandler) {
			AlertDialog.Builder builder = new AlertDialog.Builder(_context);
			builder.setTitle(title);
			builder.setMessage(Html.fromHtml(message));
			builder.setCancelable(false);
			builder.setPositiveButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					System.exit(0);
				}
			});
			builder.setIcon(icon);
			builder.show();
		}
		
		
}